﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace TotalApplication.AngelSix
{
    /// <summary>
    /// The TextEntry Width Match attached property for a <see cref="TextEntryControl"/>
    /// </summary>
    public class TextEntryWidthMatchProperty : BaseAttachedProperty<TextEntryWidthMatchProperty, bool>
    {
        public override void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            // Get the caller
            var panel = sender as Panel;

            // Make sure it is exists
            if (panel == null)
                return;

            RoutedEventHandler? onLoaded = null;
            onLoaded = (s, se) =>
            {
                // Unhook
                panel.Loaded -= onLoaded;

                SetWidths(panel);

                foreach (var child in panel.Children)
                {
                    if (child is TextEntryControl textEntry)
                    {
                        textEntry.label.SizeChanged += (s2, se2) => SetWidths(panel);
                    }
                    if (child is PasswordEntryControl passwordEntry)
                    {
                        passwordEntry.label.SizeChanged += (s2, se2) => SetWidths(panel);
                    }
                }
            };

            panel.Loaded += onLoaded;
        }

        private void SetWidths(Panel panel)
        {
            var maxWidth = 0.0d;

            foreach (var child in panel.Children)
            {
                if (child is TextEntryControl textEntry)
                {
                    //maxWidth = Math.Max(maxWidth, textEntry.label.ActualWidth);
                    maxWidth = Math.Max(maxWidth, textEntry.label.RenderSize.Width + textEntry.label.Margin.Left + textEntry.label.Margin.Right);
                    continue;
                }
                if (child is PasswordEntryControl passwordEntry)
                {
                    maxWidth = Math.Max(maxWidth, passwordEntry.label.RenderSize.Width + passwordEntry.label.Margin.Left + passwordEntry.label.Margin.Right);
                }
            }

            foreach (var child in panel.Children)
            {
                if (child is TextEntryControl textEntry)
                {
                    textEntry.LabelWidth = new GridLength(maxWidth);
                    continue;
                }
                if (child is PasswordEntryControl passwordEntry)
                {
                    passwordEntry.LabelWidth = new GridLength(maxWidth);
                }
            }
        }
    }


   
}
